package com.example8.web_flux_module.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @Description
 * @Author lihw
 * @Date 2024/1/9 15:14
 */
@RestController
@RequestMapping("/get/api")
public class GetApiController {


    @GetMapping("msg")
    public Mono<String> getMsg() {
        return Mono.just("hello flux");
    }

    @GetMapping("msg2")
    public Mono<String> getMsg2(@RequestParam("name") String name) {
        return Mono.just("hello " + name);
    }

    @GetMapping("/msg3")
    public Mono<String> getUser3() { // 异步完全没问题
        return Mono.create(sink -> {
            new Thread(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                sink.success("pq3");
            }).start();
        });
    }

    /**
     * 数据流
     *
     * @return
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> flux() {
        return Flux.create(sink -> {
            new Thread(() -> {
                String[] arr = {"pq1", "pq2", "pq3"};
                for (int i = 0; i < 3; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    sink.next(arr[i]);
                    if (i == 2) {
                        sink.complete();
                    }
                }
            }).start();
        });
    }

}
